package com.yiren.manager.ctrl.department;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.Favorites;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrCaregiver;
import com.yiren.entity.YrCaregiverSendOrdersStandard;
import com.yiren.entity.YrCgSendOrder;
import com.yiren.entity.YrCgsosSalaryDay;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderArrearage;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrElderPayRecord;
import com.yiren.entity.YrElderWallet;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.form.department.YrCaregiverForm;
import com.yiren.manager.form.department.YrCgSendOrderForm;
import com.yiren.manager.form.elder.YrElderBeHospitalForm;
import com.yiren.manager.form.elder.YrElderForm;
import com.yiren.manager.form.pension.YrCaregiverSendOrdersStandardForm;
import com.yiren.manager.service.iface.department.YrCaregiverService;
import com.yiren.manager.service.iface.department.YrCgSendOrderService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.elder.YrElderWalletService;
import com.yiren.manager.service.iface.pension.YrCaregiverSendOrdersStandardService;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("cgSendOrder")
@Controller
public class YrCgSendOrderController extends GenericController<YrCgSendOrderForm, YrCgSendOrder> {

	@Autowired
	private YrCgSendOrderService selfService;

	@Autowired
	private YrCaregiverService caregiverService;

	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;

	@Autowired
	private YrElderService elderService;

	@Autowired
	private YrCaregiverSendOrdersStandardService caregiverSendOrdersStandardService;

	@Autowired
	private YrElderWalletService elderWalletService;

	@RequestMapping("/save")
	@ResponseBody
	public HTTPResult<YrCgSendOrderForm> save(String data) throws SwallowException, MyException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
		HTTPResult<YrCgSendOrderForm> result = new HTTPResult<YrCgSendOrderForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrCgSendOrderForm form = tool.mapper("cgSendOrder", YrCgSendOrderForm.class);
		if (null == form) {
			throwExp("param.error");
		}
		String sqlWhere = "elder_id=?1 AND status=0";
		QueryResult<YrCgSendOrder> qrCgSendOrder = selfService.find(YrCgSendOrder.class, sqlWhere,
				new Object[] { form.getElderId() });
		if (qrCgSendOrder.getTotalRecord() > 0) {
			throwExp("该老者派单尚有未结束派单服务，请勿重复派单");
		}
		if (null == form.getCgSendOrderId() || form.getCgSendOrderId().isEmpty()) {
			form.setCgSendOrderId(UUIDGenerator.getUUID());
			form.setCreateTime(new Date());
			form.setStatus(0);
		}
		form.setUpdateTime(new Date());
		YrCgSendOrder entity = ObjectUtils.objectToObject(form, YrCgSendOrder.class);
		selfService.save(entity);

		return result;
	}

	@RequestMapping("findCaregiverDetail")
	@ResponseBody
	public HTTPResult<YrCaregiverForm> findCaregiverDetail(String searchVal, String subjectRoomId) throws MyException,
			InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		HTTPResult<YrCaregiverForm> result = new HTTPResult<YrCaregiverForm>();
		if (searchVal == null || subjectRoomId == null) {
			throwExp("参数有误");
		}
		String sqlWhere = "(name=?1 OR card_id=?2) AND subject_room_id=?3";
		QueryResult<YrCaregiver> qrCaregiver = caregiverService.find(YrCaregiver.class, sqlWhere,
				new Object[] { searchVal, searchVal, subjectRoomId });
		if (qrCaregiver.getTotalRecord() < 1) {
			throwExp("此科室查无该护理员的相关信息");
		}
		YrCaregiver caregiver = qrCaregiver.getResultList().get(0);
		YrCaregiverForm caregiverForm = ObjectUtils.objectToObject(caregiver, YrCaregiverForm.class);

		sqlWhere = "caregiver_id=?1 AND status=0";
		QueryResult<YrCgSendOrder> qr = selfService.find(YrCgSendOrder.class, sqlWhere,
				new Object[] { caregiver.getCaregiverId() });

		List<YrElderBeHospitalForm> elderBeHospitalForms = new ArrayList<YrElderBeHospitalForm>();
		for (YrCgSendOrder entity : qr.getResultList()) {
			String elderId = entity.getElderId();
			sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
					sqlWhere, new Object[] { elderId });
			if (qrElderBeHospital.getTotalRecord() > 0) {
				YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
				YrElderBeHospitalForm elderBeHospitalForm = ObjectUtils.objectToObject(elderBeHospital,
						YrElderBeHospitalForm.class);
				YrElder elder = elderService.findOne(elderId);
				if (null != elder) {
					elderBeHospitalForm.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
				}
				elderBeHospitalForms.add(elderBeHospitalForm);
			}
		}
		caregiverForm.setElderBeHospitalForms(elderBeHospitalForms);
		if(caregiver.getCaregiverSendOrdersStandardId()!=null){
			YrCaregiverSendOrdersStandard caregiverSendOrdersStandard = caregiverSendOrdersStandardService
					.findOne(caregiver.getCaregiverSendOrdersStandardId());
			if (null != caregiverSendOrdersStandard) {
				YrCaregiverSendOrdersStandardForm sendOrdersStandardForm = ObjectUtils
						.objectToObject(caregiverSendOrdersStandard, YrCaregiverSendOrdersStandardForm.class);
				caregiverForm.setCaregiverSendOrdersStandardForm(sendOrdersStandardForm);
			}
		}

		List<YrCaregiverForm> formList = new ArrayList<YrCaregiverForm>();
		formList.add(caregiverForm);

		result.setData(formList);

		return result;
	}

	@RequestMapping("findAll")
	@ResponseBody
	public HTTPResult<YrCgSendOrderForm> findAll() throws Exception {
		HTTPResult<YrCgSendOrderForm> result = new HTTPResult<YrCgSendOrderForm>();

		List<YrCgSendOrder> entityList = selfService.findAll();
		List<YrCgSendOrderForm> formList = new ArrayList<YrCgSendOrderForm>();
		for (YrCgSendOrder entity : entityList) {
			YrCgSendOrderForm form = toForm(entity);

			YrCaregiver caregiver = caregiverService.findOne(form.getCaregiverId());
			if (null != caregiver) {
				form.setCaregiverForm(ObjectUtils.objectToObject(caregiver, YrCaregiverForm.class));
			}

			String sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
					sqlWhere, new Object[] { entity.getElderId() });
			if (qrElderBeHospital.getTotalRecord() > 0) {
				YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
				form.setElderBeHospitalForm(ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class));
			}
			formList.add(form);
		}

		result.setData(formList);
		return result;
	}

	@RequestMapping("findBySubjectRoomId")
	@ResponseBody
	public HTTPResult<YrCgSendOrderForm> findBySubjectRoomId(String subjectRoomId) throws Exception {
		HTTPResult<YrCgSendOrderForm> result = new HTTPResult<YrCgSendOrderForm>();
		String sqlWhere = "subject_room_id=?1";
		QueryResult<YrCgSendOrder> qr = selfService.find(YrCgSendOrder.class, sqlWhere, new Object[] { subjectRoomId });

		List<YrCgSendOrder> entityList = qr.getResultList();
		List<YrCgSendOrderForm> formList = new ArrayList<YrCgSendOrderForm>();
		for (YrCgSendOrder entity : entityList) {
			YrCgSendOrderForm form = toForm(entity);

			YrCaregiver caregiver = caregiverService.findOne(form.getCaregiverId());
			if (null != caregiver) {
				form.setCaregiverForm(ObjectUtils.objectToObject(caregiver, YrCaregiverForm.class));
			}

			sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
					sqlWhere, new Object[] { entity.getElderId() });
			if (qrElderBeHospital.getTotalRecord() > 0) {
				YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
				form.setElderBeHospitalForm(ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class));
			}
			formList.add(form);
		}

		result.setData(formList);
		return result;
	}

	/**
	 * 结束服务
	 * 
	 * @param id
	 * @return
	 * @throws MyException
	 */
	// todo
	@RequestMapping("finish")
	@ResponseBody
	public HTTPResult<YrCgSendOrderForm> finish(String id, Integer calSalay) throws MyException {
		HTTPResult<YrCgSendOrderForm> result = new HTTPResult<YrCgSendOrderForm>();
		if (id == null) {
			throwExp("参数有误");
		}
		YrCgSendOrder entity = selfService.findOne(id);
		if (entity == null) {
			throwExp("该派单不存在");
		}
		if (entity.getStatus() == 1) {
			throwExp("该派单已结束，请勿重复提交");
		}
		YrCaregiver caregiver = caregiverService.findOne(entity.getCaregiverId());
		if(caregiver==null){
			throwExp("护理员不存在");
		}
		if (entity.getCaregiverSendOrdersStandardId() == null) {
			throwExp("该派单无派单标准");
		}
		YrCaregiverSendOrdersStandard sendOrdersStandard = caregiverSendOrdersStandardService
				.findOne(caregiver.getCaregiverSendOrdersStandardId());
		if (null == sendOrdersStandard) {
			throwExp("该护理员所绑定的派单标准不存在");
		}
		YrCgsosSalaryDay cgsosSalaryDay = null;
		if (calSalay == 1) {// 如果需要计算工资
			String sqlWhere = "status=0 AND caregiver_id=?1";
			QueryResult<YrCgSendOrder> qrCgSendOrder = selfService.find(YrCgSendOrder.class, sqlWhere, new Object[]{caregiver.getCaregiverId()});
			if(qrCgSendOrder.getTotalRecord()>2){
				throwExp("该护理员尚有其他派单未结束，不能结算工资");
			}
			cgsosSalaryDay = new YrCgsosSalaryDay();
			cgsosSalaryDay.setCgsosSalaryDayId(UUIDGenerator.getUUID());
			cgsosSalaryDay.setCaregiverId(entity.getCaregiverId());
			cgsosSalaryDay.setCaregiverName(entity.getCaregiverName());
			cgsosSalaryDay.setSalary(sendOrdersStandard.getSalary());
			cgsosSalaryDay.setGrantStatus(0);// 设置未发放状态
			cgsosSalaryDay.setSubjectRoomId(entity.getSubjectRoomId());
			cgsosSalaryDay.setHandleId("-1");
			cgsosSalaryDay.setCreateId("-1");
			cgsosSalaryDay.setUpdateId("-1");
			cgsosSalaryDay.setCreateTime(new Date());
			cgsosSalaryDay.setDate(new Date());
			cgsosSalaryDay.setSendStandardName(sendOrdersStandard.getStandardName());

		}

//		YrElder elder = elderService.findOne(entity.getElderId());
//		if (null == elder) {
//			throwExp("查询不到被派单的相关老者");
//		}
//
//		// 扣除老者的护理费费用
//		String sqlWhereElderWallet = "elder_id=?1";
//		QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhereElderWallet,
//				new Object[] { entity.getElderId() });
//		Date date = new Date();
//
//		YrElderWallet elderWallet = null;
//		YrElderArrearage elderArrearage = null;
//		YrElderPayRecord elderPayRecord = null;
//
//		if (qrElderWallet.getTotalRecord() > 0) {
//
//			elderWallet = qrElderWallet.getResultList().get(0);
//			// Float money;
//			String sqlWhere = "elder_id=?1 AND be_status=0";
//			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
//					sqlWhere, new Object[] { elder.getElderId() });
//			if (qrElderBeHospital.getTotalRecord() == 0) {
//				throwExp("查询不到老者入院登记信息");
//			}
//			YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
//			if (elderWallet.getWalletBalance() - sendOrdersStandard.getSalary() >= 0) {
//				elderPayRecord = new YrElderPayRecord();
//				elderPayRecord.setElderPayRecordId(UUIDGenerator.getUUID());
//				elderPayRecord
//						.setCostDesc(sendOrdersStandard.getStandardName() + " " + sendOrdersStandard.getSalary() + "元");
//				elderPayRecord.setElderCardId(elder.getCardId());
//				elderPayRecord.setPayDate(new Date());
//				elderPayRecord.setElderId(entity.getElderId());
//				elderPayRecord.setPayStatus(1);
//				elderPayRecord.setPayWay(1);
//				elderPayRecord.setCostType(3);
//				elderPayRecord.setCreateTime(new Date());
//				elderPayRecord.setRelationId(entity.getCgSendOrderId());
//				elderPayRecord.setElderName(elder.getName());
//				// 钱包余额充足
//				elderWallet.setWalletBalance(elderWallet.getWalletBalance() - sendOrdersStandard.getSalary());
//				elderPayRecord.setPayMoney(sendOrdersStandard.getSalary());
//				elderPayRecord.setSubjectRoomId(elderBeHospital.getSubjectRoomId());
//				// indiServiceCostRecord.setCostMoney(entity.getIndiServicePrice());
//			} else {// 余额不足，增加一条欠费记录
//				// elderWallet.setWalletBalance(Float.valueOf(0));//扣光钱包剩下的钱
//				// elderPayRecord.setPayMoney(elderWallet.getWalletBalance());
//				// money = elderWallet.getWalletBalance() -
//				// entity.getIndiServicePrice();
//				elderArrearage = new YrElderArrearage();
//				elderArrearage.setElderArrearageId(UUIDGenerator.getUUID());
//				elderArrearage.setSubjectRoomId(elderBeHospital.getSubjectRoomId());
//				elderArrearage.setArrearageMoney(sendOrdersStandard.getSalary());
//				elderArrearage.setArrearageReason("钱包余额不足");
//				elderArrearage.setArrearageType(3);// 设置欠费类型为个性服务费
//				elderArrearage.setElderId(entity.getElderId());
//				elderArrearage.setElderName(entity.getElderName());
//				if (null != elder) {
//					elderArrearage.setElderCardId(elder.getCardId());
//				}
//				elderArrearage.setShouldPayDate(date);
//				elderArrearage.setStatus(0);
//				elderArrearage.setCreateTime(date);
//				elderArrearage.setRelationId(entity.getCgSendOrderId());
//				elderArrearage.setArrearagePayWay(-1);
//			}
//		} else {
//			throwExp("该老者尚未有钱包，扣费失败");
//		}
		entity.setStatus(1);// 设置为结束状态

		Favorites favorites = new Favorites();
		favorites.putFavorite(YrCgSendOrder.class, entity);
//		favorites.putFavorite(YrElderWallet.class, elderWallet);
//		favorites.putFavorite(YrElderArrearage.class, elderArrearage);
//		favorites.putFavorite(YrElderPayRecord.class, elderPayRecord);
		favorites.putFavorite(YrCgsosSalaryDay.class, cgsosSalaryDay);

		selfService.executefinish(favorites);
		return result;
	}

	// @RequestMapping("finishBatch")
	// @ResponseBody
	// public HTTPResult<YrCgSendOrderForm> finishBatch(String data) throws
	// MyException, SwallowException{
	// HTTPResult<YrCgSendOrderForm> result = new
	// HTTPResult<YrCgSendOrderForm>();
	// JsonMapperTool tool = new JsonMapperTool(data);
	// String[] ids = tool.mapper("ids", String[].class);
	// if(null==ids){
	// throwExp("param.error");
	// }
	// for(String id : ids){
	// YrCgSendOrder entity = selfService.findOne(id);
	// entity.setStatus(1);
	// selfService.save(entity);
	// }
	// return result;
	// }

	@Override
	public YrCgSendOrderForm toForm(YrCgSendOrder e) throws Exception {
		YrCgSendOrderForm form = ObjectUtils.objectToObject(e, YrCgSendOrderForm.class);
		return form;
	}

	@Override
	public YrCgSendOrder toEntity(YrCgSendOrderForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
